<template>
  <Transition name="fade" @after-leave="destoryComponent" @enter="updateHeight">
    <div
      v-show="isShow"
      ref="messageRef"
      class="lt_message"
      :class="{ [` message_${type}`]: true }"
      :style="{ top: `${offsetTop}px` }"
    >
      <div class="message_content">
        <span>{{ message }}</span>
      </div>
      <div v-if="showClose" class="message_close">
        <closeIcon size="16" @click="isShow = false" />
      </div>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef } from 'vue'
import closeIcon from './icon/close-icon.vue'
import { IMessageProps } from './type'
import { getLastMessageTopDistance } from './message'

const props = withDefaults(defineProps<IMessageProps>(), {
  message: '默认提示信息',
  duration: 3000,
  showClose: true,
  offset: 20,
  type: 'info'
})

const isShow = ref(false)
const startTimer = () => {
  if (props.duration === 0) return
  setTimeout(() => {
    isShow.value = false
  }, props.duration)
}

onMounted(async () => {
  isShow.value = true
  startTimer()
})

const messageRef = useTemplateRef<HTMLDivElement>('messageRef')
const height = ref(0)

// 获得最后一个message的向上偏移值(top)
const lastOffsetTop = computed(() => getLastMessageTopDistance(props.id!))
// 这个元素的top值
const offsetTop = computed(() => lastOffsetTop.value + props.offset)
// 为下一个message预留的top值
const nextOffsetTop = computed(() => offsetTop.value + height.value)

// watch(isShow, (newVal) => {
//   if (!newVal) {
//     props.destory && props.destory()
//   }
// })

const destoryComponent = () => {
  props.destory && props.destory()
}
const updateHeight = () => {
  height.value = messageRef.value?.getBoundingClientRect().height || 0
}

defineExpose({
  nextOffsetTop
})
</script>

<style scoped lang="scss">
.lt_message {
  position: fixed;
  left: 50%;
  top: 0;
  z-index: 9999;
  transform: translateX(-50%);
  padding: 8px 15px;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  border-radius: 5px;
  box-sizing: border-box;

  .message_content {
    cursor: pointer;
  }
}

.message_info {
  color: #fff;
  background-color: #909399;
  border-color: #909399;
}
.message_success {
  color: #fff;
  background-color: #67c23a;
  border-color: #67c23a;
}
.message_warning {
  color: #fff;
  background-color: #e6a23c;
  border-color: #e6a23c;
}
.message_error {
  color: #fff;
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.fade-enter-from,
.fade-leave-to {
  transform: translateY(-50%) translateX(-50%);
  opacity: 0;
}
.fade-enter-to,
.fade-leave-from {
  transform: translateY(0) translateX(-50%);
  opacity: 1;
}
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s;
}
</style>
